package com.qbccn.onlinetest.service.impl;

import com.qbccn.onlinetest.service.ResdisService;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

/**
 * @author linke
 * @date 2020/7/12 15:52
 * @description
 */
@Service
public class ResdisServiceImpl implements ResdisService {

  @Autowired
  private RedisTemplate redisTemplate;

  /**
   * 序列化key，在redis中可以看到原本的内容
   * key赋值归类： my_key:my_value
   */
  @Autowired(required = false)
  public void setRedisTemplate(RedisTemplate redisTemplate) {
    RedisSerializer stringSerializer = new StringRedisSerializer();
    redisTemplate.setKeySerializer(stringSerializer);
//    redisTemplate.setValueSerializer(stringSerializer);
//        redisTemplate.setHashKeySerializer(stringSerializer);
//        redisTemplate.setHashValueSerializer(stringSerializer);
    this.redisTemplate = redisTemplate;
  }

  @Override
  public void set(String key, Object value, int seconds) {
    redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
  }

  @Override
  public Object get(String key) {
    return redisTemplate.opsForValue().get(key);
  }

  @Override
  public boolean delete(String key) {
    return redisTemplate.delete(key);
  }

  @Override
  public List<Object> getByLike(String key) {
    Set<Object> s = redisTemplate.keys(key);
    return new ArrayList<>(s);
  }
}
